// 聊天室
const ws = require('nodejs-websocket')
const PORT = 8088

// 接收到消息广播给所有用户
const broadcast = (server, data) => {
  server.connections.forEach(function (socket) {
    socket.sendText(data)
  })
}

let socketServer = ws.createServer(function (socket) {
  socket.on('text', function (res) {
    // 心跳不处理
    if (res === '_this_is_socket_heart') return

    console.log('客户端发送过来的数据：' + res)

    // 广播
    broadcast(socketServer, res)
  })

  socket.on('close', function (code, reason) {
    console.log('socket 链接关闭，关闭代码：' + code + '，关闭原因：' + reason)
  })

  socket.on('error', function (err) {
    console.log('socket 链接错误：', err)
  })
})
socketServer.listen(PORT)
console.log('websocket server listening on port：' + PORT)